//
//  EditViewController.m
//  便签
//
//  Created by  on 2022/9/29.
//

#import "EditViewController.h"
#import "EditCell.h"
#import "EditHeader.h"
#import "EditFlowLayout.h"
#import "NewSignViewController.h"

@interface EditViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic) IBOutlet UIButton *fontBtn;
@property (strong, nonatomic) IBOutlet UIButton *boldBtn;
@property (strong, nonatomic) IBOutlet UIButton *colorBtn;
@property (strong, nonatomic) IBOutlet UIButton *picBtn;
@property (strong, nonatomic) UIButton *rightBtn;
@property (strong, nonatomic) UIButton *rightBtn2;
@property (strong, nonatomic) EditHeader *header;
@property (nonatomic, assign) int done;
@end

@implementation EditViewController
-  (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.model.sign == nil) {
        WS(self)
        NewSignViewController *vc = [NewSignViewController new];
        vc.block = ^(SignModel * _Nonnull model) {
            weakself.model.sign = model;
        };
        [self presentViewController:vc animated:NO completion:nil];
    }
}
- (void)initUI{
    self.title = [NSDate transToDate:@"yyyy.MM.dd" :self.model.stamp];
    [self.backBtn setImage:[UIImage imageNamed:@"返回_黑色箭头_实心"] forState:UIControlStateNormal];
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightBtn.tag = 205;
    self.rightBtn.frame = CGRectMake(0, StuBarHight + 5, 40, 34);
    [self.rightBtn addTarget:self action:@selector(actionForBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.rightBtn setTitleColor:[UIColor colorHex:@"#1A1A1A"] forState:UIControlStateNormal];
    [self.rightBtn setImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
    UIBarButtonItem *item =[[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    
    self.rightBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightBtn2.tag = 206;
    self.rightBtn2.frame = CGRectMake(0, StuBarHight + 5, 40, 34);
    [self.rightBtn2 addTarget:self action:@selector(actionForBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.rightBtn2 setTitleColor:[UIColor colorHex:@"#1A1A1A"] forState:UIControlStateNormal];
    if (self.isedit) {
        [self.rightBtn2 setImage:[UIImage imageNamed:@"编辑"] forState:UIControlStateNormal];
        [self.rightBtn2 setTitle:LS(@"保存") forState:UIControlStateSelected];
    }else{
        self.rightBtn2.selected = YES;
        [self.rightBtn2 setTitle:LS(@"保存") forState:UIControlStateNormal];
        [self actionForBtn:self.rightBtn2];
    }
    UIBarButtonItem *item2 =[[UIBarButtonItem alloc] initWithCustomView:self.rightBtn2];
    self.navigationItem.rightBarButtonItems = self.isedit ? @[item2,item]:@[item2];
    
    CGFloat w = (SCREEN_WIDTH - 20 * 2) - 12 * 2 ;
    CGFloat h = 150 / 140.0 * w;
    EditFlowLayout *flowlayout = [[EditFlowLayout alloc] init];
    flowlayout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH - 40, 300);
    flowlayout.itemSize = CGSizeMake(w, h);
    flowlayout.minimumLineSpacing = 20;
    flowlayout.minimumInteritemSpacing = 20;
    flowlayout.sectionInset = UIEdgeInsetsMake(20, 0, 85, 0);
    self.collectionView.collectionViewLayout = flowlayout;
    [self.collectionView registerNib:[EditCell nib] forCellWithReuseIdentifier:[EditCell ID]];
    [self.collectionView registerNib:[EditHeader nib] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[EditHeader ID]];
    NSLayoutConstraint *top = [self.collectionView a1:NSLayoutAttributeTop e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeTop c:0];
    NSLayoutConstraint *left = [self.collectionView a1:NSLayoutAttributeLeft e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeLeft c:20];
    NSLayoutConstraint *right = [self.collectionView a1:NSLayoutAttributeRight e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeRight c:-20];
    NSLayoutConstraint *bottom = [self.collectionView a1:NSLayoutAttributeBottom e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeBottom c:0];
    [self.view addConstraints:@[top,left,right,bottom]];
    
    [self.view bringSubviewToFront:self.fontBtn];
    [self.view bringSubviewToFront:self.boldBtn];
    [self.view bringSubviewToFront:self.colorBtn];
    [self.view bringSubviewToFront:self.picBtn];
    
}
- (IBAction)actionForBtn:(UIButton *)sender {
    WS(self)
    if (sender.tag == 201) {
        PickViewController * vc = [PickViewController new];
        NSArray *array = @[@[@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26"]];
        vc.array = array;
        vc.block = ^(NSMutableArray *selecIndexarray) {
            NSInteger index = [selecIndexarray[0] intValue];
            weakself.model.font = array[0][index];
            [weakself.collectionView reloadData];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }else if (sender.tag == 202){
        sender.selected = !sender.selected;
        sender.backGroudHexColor = sender.selected ? @"#CACACA" : @"#FD9C14";
        weakself.model.bold = sender.selected;
        [weakself.collectionView reloadData];
    }else if (sender.tag == 203){
        [ColorViewController pop:^(NSString * _Nonnull hexColor) {
            weakself.model.hexcolor = hexColor;
            [weakself.collectionView reloadData];
        }];
    }else if (sender.tag == 204){
        SheetViewController *vc = [SheetViewController new];
        vc.withCancel = NO;
        vc.array = @[@"相机",@"从图库中选择"];
        vc.block = ^(int index, NSString * _Nonnull text) {
            [weakself ImagePicker:(UIImagePickerControllerSourceType)index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }else if (sender.tag == 205){///删除
        NSString* where = [NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"account"),bg_sqlValue(self.model.account),bg_sqlKey(@"ID"),bg_sqlValue(self.model.ID)];
        [NoteModel bg_deleteAsync:nil where:where complete:^(BOOL isSuccess) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:notifyNoteUpdate object:nil];
                [self backBtnAction];
            });
        }];
    }else if (sender.tag == 206){
        if (self.isedit) {
            sender.selected = !sender.selected;
            [sender setImage:[UIImage imageNamed: sender.selected ? @"" : @"编辑"] forState:UIControlStateNormal];
            self.done += 1;
            self.header.inputView.userInteractionEnabled = self.done >= 1;
        }else{
            sender.selected = YES;
        }
        self.fontBtn.hidden = !sender.selected;
        self.boldBtn.hidden = !sender.selected;
        self.colorBtn.hidden = !sender.selected;
        self.picBtn.hidden = !sender.selected;
        if (sender.selected) {
            if (self.model.content.length <= 0) {
                return [Toast startHud:LS(@"内容不能为空") stopTime:1 handle:nil];
            }
        }
        if (self.isedit && self.done <= 1) {
            return;
        }
        [Toast msg:LS(@"保存中...")];
        
        [self.model.sign bg_saveOrUpdateAsync:^(BOOL isSuccess) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:notifySignUpdate object:nil];
            });
        }];
        [self.model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [Toast stopHud];
                [[NSNotificationCenter defaultCenter] postNotificationName:notifyNoteUpdate object:nil];
                [self backBtnAction];
            });
        }];
    }
}
- (NoteModel *)model{
    if (!_model) {
        _model = [NoteModel new];
    }
    return _model;
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    NSData *data = UIImageJPEGRepresentation(img, 0.5);
    [self.model.data addObject:data];
    [self.collectionView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  self.model.data.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    EditCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[EditCell ID] forIndexPath:indexPath];
    cell.img.image = [UIImage imageWithData:self.model.data[indexPath.row]];
    WS(self)
    cell.block = ^{
        if (self.isedit && self.done < 1) {
            return;
        }
        [weakself.model.data removeObjectAtIndex:indexPath.row];
        [weakself.collectionView reloadData];
    };
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    self.header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[EditHeader ID] forIndexPath:indexPath];
    self.header.model = self.model;
    self.header.inputView.userInteractionEnabled = !self.isedit || self.done>= 1;
    WS(self)
    self.header.block = ^(NSInteger tag) {
        if (weakself.isedit == NO || self.done >= 1) {
            SheetViewController *vc = [SheetViewController new];
            vc.withCancel = NO;
            vc.array = @[@"白多云",@"暴雨",@"大风",@"晴天",@"闪电",@"雪",@"夜多云",@"夜闪电",@"阴天",@"中雨"];
            WS(vc)
            vc.block = ^(int index, NSString * _Nonnull text) {
                weakself.model.weather = weakvc.array[index];
                [weakself.collectionView reloadData];
            };
            [weakself presentViewController:vc animated:NO completion:nil];
        }
    };
    return  self.header;
}
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
}
@end
